package com.ideaaedi.mybatis.data.security.config;

import com.ideaaedi.mybatis.data.security.interceptor.MybatisEncryptPlugin;
import com.ideaaedi.mybatis.data.security.support.EncryptExecutor;
import com.ideaaedi.mybatis.data.security.support.EncryptParser;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * 总配置类
 *
 * @author JustryDeng
 * @since 2021/7/19 2:49:24
 */
@org.springframework.context.annotation.Configuration
@AutoConfigureAfter(value = {Configuration.class, SqlSessionFactory.class})
public class MybatisDataSecurityConfiguration {
    
    /**
     * 解析器
     */
    @Bean
    public EncryptParser encryptParser(@Autowired ApplicationContext applicationContext, @Autowired EncryptExecutor encryptExecutor) {
        EncryptParser encryptParser = new EncryptParser(applicationContext, encryptExecutor);
        // 添加mybatis拦截器
        addInterceptor(encryptParser);
        return encryptParser;
    }
    
    /**
     * 添加mybatis拦截器
     */
    private void addInterceptor(EncryptParser encryptParser) {
        MybatisEncryptPlugin mybatisEncryptPlugin = new MybatisEncryptPlugin(encryptParser);
        encryptParser.getSqlSessionFactoryList().forEach(sqlSessionFactory -> {
            Configuration configuration = sqlSessionFactory.getConfiguration();
            if (configuration == null) {
                return;
            }
            configuration.addInterceptor(mybatisEncryptPlugin);
        });
    }
}
